package com.mall.user.intercepter;

import com.alibaba.fastjson.JSON;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.util.IJwtTokenUtils;
import com.mall.user.annotation.Anonymous;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 用来实现token拦截认证
 * <p>
 * 其实就是用来判断当前这个操作是否需要登录
 */
public class TokenIntercepter extends HandlerInterceptorAdapter {

//    @Reference(timeout = 3000,check = false)
//    ILoginService iUserLoginService;

    public static String ACCESS_TOKEN = "access_token";

    public static String USER_INFO_KEY = "userInfo";

    @Reference(check = false)
    IJwtTokenUtils jwtTokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // handler = 请求的目标controller的对象
        // 判断我们请求的对象是不是一个HandlerMethod类型的对象
        // 什么样的对象是一个HandlerMethod对象呢？ 动态请求请求的Controller对象就是HandlerMethod对象
        // 假如这个请求是一个静态资源的请求，那么就不是HandlerMethod类型的对象
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 强转
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 判断
        if (isAnoymous(handlerMethod)) {
            return true;
        }

        // 从cookie里面去取token ，这个token，就是JWT token
        String token = CookieUtil.getCookieValue(request, ACCESS_TOKEN);
        if (StringUtils.isEmpty(token)) {
            ResponseData responseData = new ResponseUtil().setErrorMsg("token已失效");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSON(responseData).toString());
            return false;
        }
        //将token的json字符串传入USER_INFO_KEY
        jwtTokenUtils.setToken(token);
        String userTokenJson = jwtTokenUtils.freeJwt();
        request.setAttribute(USER_INFO_KEY,userTokenJson);

        //从token中获取用户信息
//        CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
//        checkAuthRequest.setToken(token);
//        CheckAuthResponse checkAuthResponse=iUserLoginService.validToken(checkAuthRequest);
//        if(checkAuthResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
//            request.setAttribute(USER_INFO_KEY,checkAuthResponse.getUserinfo()); //保存token解析后的信息后续要用
//            return super.preHandle(request, response, handler);
//        }
//        ResponseData responseData=new ResponseUtil().setErrorMsg(checkAuthResponse.getMsg());
//        response.setContentType("text/html;charset=UTF-8");
//        response.getWriter().write(JSON.toJSON(responseData).toString());
        //非空判断是否在正确
        return true;
    }


    private boolean isAnoymous(HandlerMethod handlerMethod) {

        // 获取目标Controller对象实例
        Object bean = handlerMethod.getBean();
        // 获取实例的Class对象
        Class clazz = bean.getClass();

        // 通过实例对象，获取实例类上的注解   反射
        if (clazz.getAnnotation(Anonymous.class) != null) {
            return true;
        }

        // 获取方法实例
        Method method = handlerMethod.getMethod();

        // 通过方法实例对象，获取Anoymous注解 如果为空，返回false，如果不为空，就返回true
        return method.getAnnotation(Anonymous.class) != null;
    }
}
